//
// Created by alexander on 12/22/18.
//
#include <stdio.h>
#include <libavformat/avformat.h>
#include </home/alexander/CLionProjects/FFmpegLogTest/log/log.h>
#include </home/alexander/CLionProjects/FFmpegLogTest/util/util.h>
#include <stdbool.h>

#define CurrentDir "/home/alexander/CLionProjects/FFmpegLogTest/"
int returnCode;

/**给每一帧音频数据添加adts头，要不然aac文件无法播放
 * @param szAdtsHeader adts头的数组地址
 * @param dataLen 接受此adts头的aac数据长度
 */
void adts_header(char *szAdtsHeader, int dataLen)
{
    int audio_object_type = 2;
    int sampling_frequency_index = 7;
    int channel_config = 2;

    int adtsLen = dataLen + 7;

    szAdtsHeader[0] = 0xff;         //syncword:0xfff                          高8bits
    szAdtsHeader[1] = 0xf0;         //syncword:0xfff                          低4bits
    szAdtsHeader[1] |= (0 << 3);    //MPEG Version:0 for MPEG-4,1 for MPEG-2  1bit
    szAdtsHeader[1] |= (0 << 1);    //Layer:0                                 2bits
    szAdtsHeader[1] |= 1;           //protection absent:1                     1bit

    szAdtsHeader[2] = (audio_object_type - 1)<<6;            //profile:audio_object_type - 1                      2bits
    szAdtsHeader[2] |= (sampling_frequency_index & 0x0f)<<2; //sampling frequency index:sampling_frequency_index  4bits
    szAdtsHeader[2] |= (0 << 1);                             //private bit:0                                      1bit
    szAdtsHeader[2] |= (channel_config & 0x04)>>2;           //channel configuration:channel_config               高1bit

    szAdtsHeader[3] = (channel_config & 0x03)<<6;     //channel configuration:channel_config      低2bits
    szAdtsHeader[3] |= (0 << 5);                      //original：0                               1bit
    szAdtsHeader[3] |= (0 << 4);                      //home：0                                   1bit
    szAdtsHeader[3] |= (0 << 3);                      //copyright id bit：0                       1bit
    szAdtsHeader[3] |= (0 << 2);                      //copyright id start：0                     1bit
    szAdtsHeader[3] |= ((adtsLen & 0x1800) >> 11);           //frame length：value   高2bits

    szAdtsHeader[4] = (uint8_t)((adtsLen & 0x7f8) >> 3);     //frame length:value    中间8bits
    szAdtsHeader[5] = (uint8_t)((adtsLen & 0x7) << 5);       //frame length:value    低3bits
    szAdtsHeader[5] |= 0x1f;                                 //buffer fullness:0x7ff 高5bits
    szAdtsHeader[6] = 0xfc;
}

int extraAudio(const char *srcFileName, const char *destFileName)
{
    setLogLevel(AV_LOG_DEBUG);

    AVFormatContext *avFormatContext = NULL;
    FILE *destOutputFile = NULL;
    AVPacket avPacket;

    av_register_all();

    /*打开输入文件*/
    returnCode = avformat_open_input(&avFormatContext, srcFileName, NULL, NULL);
    if(returnCode < 0)
    {
        logError("Open input file error, code is %d\n", (int *) returnCode);
        goto __faile;
    }
    /*先打印基本信息*/
    av_dump_format(avFormatContext, 0, srcFileName, 0);

    /*获取audio_stream*/
    int audioStreamIndex = av_find_best_stream(avFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
    if(audioStreamIndex < 0)
    {
        logError("Could not find audio stream in input file %s\n", srcFileName);
        goto __faile;
    }

    /*打开目标输出文件，为写入音频数据做准备*/
    destOutputFile = fopen(destFileName, "wb");
    if(destOutputFile == NULL)
    {
        logError("Open destOutputFile error, code is %d\n", (int *) returnCode);
        goto __faile;
    }

    av_init_packet(&avPacket);
    avPacket.data = NULL;
    avPacket.size = 0;
    while (av_read_frame(avFormatContext, &avPacket) >= 0)
    {
        if(avPacket.stream_index == audioStreamIndex)
        {
            /*首先写入adts头*/
            char adtsHeader[7];
            adts_header(adtsHeader, avPacket.size);
            int size = strlen(adtsHeader);
            fwrite(adtsHeader, 1, strlen(adtsHeader), destOutputFile);

            int len = fwrite(avPacket.data, 1, avPacket.size, destOutputFile);
            if(len != avPacket.size)
            {
                logError("warning, length of writed data isn't equal!", "");
                goto __faile;
            }
        }
        av_packet_unref(&avPacket);
    }

__faile:
    avformat_close_input(&avFormatContext);
    if(destOutputFile != NULL)
    {
        fclose(destOutputFile);
    }

    return returnCode;
}






















